package demo;

import java.util.Arrays;

public class Solution1 {

    //快排
    public void quickSort(int[] arr) {
        quick(arr, 0, arr.length - 1);
    }

    private int fundPoint(int[] arr, int start, int end) {
        int key = arr[start];
        while(start < end) {
            while(start < end && arr[end] >= key) {
                end--;
            }
            arr[start] = arr[end];
            while(start < end && arr[start] <= key) {
                start++;
            }
            arr[end] = arr[start];
        }
        arr[start] = key;
        return start;
    }

    private int fundMid(int[] arr, int left, int right) {
        int mid = (left + right) / 2;
        if(arr[left] < arr[right]) {
            if(arr[left] > arr[mid]) {
                return left;
            } else if(arr[mid] > arr[right]) {
                return right;
            } else {
                return mid;
            }
        } else {
            if(arr[left] < arr[mid]) {
                return left;
            } else if(arr[right] > arr[mid]) {
                return right;
            } else {
                return mid;
            }
        }
    }

    public void insertSort(int[] arr, int left, int right) {
        for(int i = left + 1; i <= right; i++) {
            int key = arr[i];
            int j = i - 1;
            for(; j >= left; j -= 1) {
                if(arr[j] > key) {
                    arr[j + 1] = arr[j];
                } else {
                    break;
                }
            }
            arr[j + 1] = key;
        }
    }

    private void quick(int[] arr, int left, int right) {
        if(left >= right) {
            return;
        }
        //递归层次优化
        if(right - left + 1 < 7) {
            insertSort(arr, left, right);
        }
        //三数取中
        int mid = fundMid(arr, left, right);
        //寻找基准
        int point = fundPoint(arr, left, right);
        quick(arr, left, point - 1);
        quick(arr, point + 1, right);
    }


    public void mergeSort(int[] arr) {
        mergeFun(arr, 0, arr.length - 1);
    }

    public void mergeFun(int[] arr, int left, int right) {
        if(left >= right) {
            return;
        }
        int mid = (left + right) / 2;
        mergeFun(arr, left, mid);
        mergeFun(arr, mid + 1, right);
        merge(arr, left, right, mid);
    }

    public void merge(int[] arr, int start, int end, int mid) {

    }

}


class Main {
    public static void main(String[] args) {
        int[] arr = {3,1,2,6,5,3,9,0};

        Solution1 solution1 = new Solution1();
        solution1.quickSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
